<template>
  <a-select v-bind="$attrs" v-on="$listeners" show-search :placeholder="placeholder" v-model="currentValue" allowClear
    :default-active-first-option="false" :filter-option="false" @search="handleSearch" @popupScroll="onPopupScroll"

    @blur="
      () => {
        isBlur ? handleSearch('') : undefined
      }
    " :getPopupContainer="getPopupContainer">
    <a-icon v-if="loading" style="color: #096dd9" slot="suffixIcon" type="loading" />
    <a-spin v-if="loading" slot="notFoundContent" size="small" />
    <a-select-option :disabled="!!i.disabled" v-for="i in duplicatedatalist" :key="i[optionKey]" :value="i[optionKey]"
      :label="i.name">
      <a-tooltip v-bind="tooltipAttrs" v-if="customRender" placement="topLeft" :mouseLeaveDelay="0"
        :getPopupContainer="popupContainer">
        <template slot="title">
          {{ customRender(i) }}
        </template>
        <div v-if="customName">{{ customName(i) }}</div>
        <div v-else>{{ i.name }}</div>
      </a-tooltip>
      <div v-else>
        <div v-if="customName">{{ customName(i) }}</div>
        <div v-else>{{ i.name }}</div>
      </div>
    </a-select-option>
  </a-select>
</template>
<script>
import { getOrgEmployeesListBy, getOneOrgUsers } from '@/api/commons'
import debounce from 'lodash/debounce'

//2021/11/16,备注：v-model绑定的值，必须在form表单里面声明，否则会出现选在第一页后面的人，无法回显的bug
//2022/01/11,备注：v-model绑定的值，必须在form表单里面声明，否则会出现，联动时watch不到变动的bug
/*
*
*
*
*
不和其他下拉框联动的，查所有人的
<ASelectOrgPeople
                                    :disabled="disabled"
                                    @onSelectChange="form.speakerName = $event.name;"
                                    :customRender="customRender"//如果你要显示其他的内容，默认是显示岗位，不想显示tooltip的话，传个null
                                    v-model="form.speakerId"
                                ></ASelectOrgPeople>

要和其他下拉框联动的，查指定单位的
  <ASelectOrgPeople
                  :disabled="disabled"
                  @onSelectChange="getPeople"
                 :init="false"是否默认加载数据，如果要联动的话，应该始终为false
                  :form="formInfo"
                  key-value="orgId"
                  v-model="formInfo.userId"
                ></ASelectOrgPeople>
*
*
*
* */
export default {
  inheritAttrs: false,
  name: 'SelectOrgPeople',
  props: {
    // v-model绑定的数据
    value: {
      type: [Array, String, Object]
    },
    // 组织id
    orgId: [String, Number, Object],
    api: {
      type: [Object, Function],
      default: () => getOneOrgUsers
    },
    optionKey: {
      type: String,
      default: () => 'userId'
    },
    // 需要联动的表单名
    keyValue: {
      type: String,
      default: () => 'test'
    },
    form: {
      type: Object,
      default: () => ({})
    },
    // placeholder
    placeholder: {
      type: String,
      default: () => '请选择'
    },
    // 是否默认加载数据，如果要联动的话，应该始终为false
    init: {
      type: Boolean,
      default: () => true
    },
    isAutoSelectMe: {
      type: Boolean,
      default: () => false
    },
    isBlur: {
      type: Boolean,
      default: () => false
    },
    //tooltip里面的内容
    //默认是显示岗位, 如果你要显示其他的内容，自己传个方法进来，不想显示tooltip的话，传个null
    customRender: {
      type: [Function],
      default: (q) => {
        let str = ''
        if (q.postPNames && q.postPNames.length) {
          str = q.postPNames.join('/')
        }
        if (str.length > 100) {
          return str.substr(0, 100) + '...'
        }
        return str
      }
    },
    customName: {
      type: [Function],
      default: (q) => {
        let str = q.name
        return str
      }
    },
    // 请求参数
    requestParams: {
      type: Object,
      default: () => null
    },
    needRootOrgId: {
      type: Boolean,
      default: false
    },
    // 悬浮框参数
    tooltipAttrs: {
      type: Object,
      default: () => null
    },
    //是否只选中本级的人员,比如四川分公司的就只能选择四川分公司的
    isRank:{
      type: Boolean,
      default: false
    },
    //是否把当前人加入进去
    isCreatorName:{
      type: Boolean,
      default: false
    },
  },
  data() {
    //防抖
    this.handleSearch = debounce(this.handleSearch, 800)
    return {
      fetching: false,
      userFetching: false,
      list: [],
      total: 0,
      pageNumber: 1,
      pageSize: 100,
      queryParams: {},
      localIsSearch: false,
      popupContainer: () => document.body
    }
  },
  watch: {
    optionKey(newVal) {
      console.log(newVal, 'newVal')
    },
    //2022-01-12
    //两个watch改为立即执行，是因为出现了一种情况，就是尽管是需要联动查寻人员
    //但是，如果form数据已经准备好了，ASelectOrgPeople当前组件，才显示出现（才挂载）
    //那么因为form数据已经准备好了，v-model和keyValue绑定的值，都没有再变动。所以watch不到变动
    attr: {
      handler(e) {
        //2022-01-12
        //不关联的情况下，才能orgId变动，去查新的人员
        //原因：
        //因为，取消了pageNumber = 1时，this.list = res.data.list的代码，不管多少页都用concat合并list数据
        //如果不判断this.init，那么orgId有值的时候，会在mounted里面请求一次，然后在当前这个watch里面又会走一次
        //尽管我在reset里面设置了this.list = []，但是两个请求几乎是同一时间发出的，两次两样请求，同样的数据会被合并到一个数组里面
        //被提示key 重复的错误
        if (!this.init) {
          if (e) {
            this.reset()
          }
          // else {
          //   this.currentValue = undefined
          // }
        }
      },
      immediate: true
    },
    currentValue: {
      handler(e) {
        e && this.findUser()
      },
      immediate: true
    },
  },
  mounted() {
    this.init && this.getList()
  },
  methods: {
    async findUser() {
      // value变动一下就查一下这个人，因为有可能编辑页面也没选数据，用localInit、isEdit来判断，不准确
      // 如果list里面没有这条数据就去库里面查一下这个人，然后赛到第一条（一般是回显的时候list才可能没得值）
      this.userFetching = true
      if (this.$attrs.mode == 'multiple') {
        let noFind = this.currentValue?.filter((e) => {
          return !this.list.find((v) => v[this.optionKey] === e)
        }).map(el=>el.key)
        if (noFind.length && this.optionKey == 'userId') {
          let p = { pageSize: noFind.length, pageNumber: 1, userIds: noFind }
          let res = await this.api(p)
          if (res.code === this.SUCCESS_CODE) {
            res.data.list.forEach((item, index) => {
              this.list.unshift(item)
            })
          }
        }
      } else {
        //判断下list里面有没有这个人，
        if (!this.list.find((v) => v[this.optionKey] === this.currentValue)) {
          let p = { pageSize: 1, pageNumber: 1 }
          p[this.optionKey] = this.currentValue
          let res = await this.api(p)
          if (res.code === this.SUCCESS_CODE && res.data.list.length === 1) {
            //再次确认下list里面有没有这个人，因为接口是await的，可能就差了那几毫秒，list突然有数据了
            if (!this.list.find((v) => v[this.optionKey] === this.currentValue)) {
              this.list.unshift(res.data.list[0])
            }
          }
        }
      }
      this.userFetching = false
    },
    getPopupContainer() {
      return document.querySelector('body')
    },
    reset() {
      this.queryParams = {}
      this.pageNumber = 1
      this.list = []
      this.getList()
    },
    handleSearch(value) {
      this.queryParams.nameLike = value
      this.localIsSearch = !!value
      this.pageNumber = 1
      this.list = []
      this.getList(this.localIsSearch)
    },
    onPopupScroll(e) {
      const { target } = e
      if (target.scrollTop + target.offsetHeight > target.scrollHeight - 5) {
        //合并用这个，不然无法触发滚动事件，andt误我
        if (this.fetching) return
        if (this.total / this.pageSize > this.pageNumber) {
          this.pageNumber = this.pageNumber + 1
          this.getList(this.localIsSearch)
        }
      }
    },
    async getList(isSearch = false) {
      let params = {
        pageSize: this.pageSize,
        pageNumber: this.pageNumber,
        ...this.queryParams
      }
      params = Object.assign({}, params, this.requestParams ? this.requestParams : { rootOrgId: this.attr })
      if (this.needRootOrgId) {
        params.rootOrgId = this.attr
      }
      if(this.isRank){
         delete params.rootOrgId;
         let rankParams = {and: true,orgId:this.attr,orgType:2};
         params = {...params,...rankParams}
      }
      this.fetching = true
      let res = await this.api(params)
      if (res) {
        this.$emit('fetch', res.list)
        //如果查的10条数据里面有已经选中的那条，就要删除掉，不然会有两个重复的数据
        if (this.currentValue && !isSearch) {
          let resIndex = res.list.findIndex((v) => v[this.optionKey] === this.currentValue)
          if (resIndex !== -1) {
            res.list.splice(resIndex, 1)
          }
        }
        this.list = this.list.concat(res.list)

        if (!isSearch) {
          //非搜索状态下自动选中自己
          if (this.isAutoSelectMe) {
            let res2 = this.list.find((v) => v[this.optionKey] === this.$userInfo().id)
            if (res2) {
              this.currentValue = res2[this.optionKey]
            }
          }
        }
        this.total = res.total
      }
      this.fetching = false
    }
  },
  computed: {
    loading() {
      return this.userFetching || this.fetching
    },
    // 需要联动的表单值
    attr() {
      if (this.form[this.keyValue]) {
        return this.form[this.keyValue]
      }
      return this.orgId
    },
    // 转换绑定的选中数据，与v-model同步
    currentValue: {
      get: function () {
        return this.value
      },
      set: function (value) {
        // console.log('currentValue-set', value)
        this.$emit('input', value)
        this.$emit('change', value)
        if (this.$attrs.mode == 'multiple') {
          let res = this.list.filter((v) => value.includes(v[this.optionKey]))
          this.$emit('onSelectChange', res || [])
        } else {
          let res = this.list.find((v) => v[this.optionKey] === value)
          if (res) {
            this.$emit('onSelectChange', res)
          } else {
            this.$emit('onSelectChange', {})
          }
        }
      }
    },
    duplicatedatalist() {
      var obj = {};
      let list = this.list.reduce(function(item, next) {
        obj[next.id] ? '' : obj[next.id] = true && item.push(next);
        return item;
      }, []);
      if(this.isCreatorName){
        let creatorName = {
          userId: this.$userInfo().employee.userId,
          name: this.$userInfo().name
        }
        let find = list.find((item)=>item.userId == this.$userInfo().employee.userId)
       !find && list.push(creatorName)

      }
      return list
    }
  }
}
</script>
